using B.S.NewMedical.Api.Read.Application.Command.MobileService.Consult;
using B.S.NewMedical.Api.Read.DTOS.Consult;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Consult
{
    /// <summary>
    /// 获取用户互动状态处理器
    /// </summary>
    public class GetUserInteractStatusHandler : IRequestHandler<GetUserInteractStatusCommand, ApiResult<UserInteractStatusDto>>
    {
        private readonly IBaseRepository<ConsultInteract> _interactRepository;
        private readonly ILogger<GetUserInteractStatusHandler> _logger;

        public GetUserInteractStatusHandler(
            IBaseRepository<ConsultInteract> interactRepository,
            ILogger<GetUserInteractStatusHandler> logger)
        {
            _interactRepository = interactRepository;
            _logger = logger;
        }

        public async Task<ApiResult<UserInteractStatusDto>> Handle(GetUserInteractStatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取用户互动状态，用户ID：{UserId}，对象类型：{ObjType}，对象ID：{ObjId}",
                    request.UserId, request.ObjType, request.ObjId);

                // 获取用户对该对象的所有互动
                var interacts = await _interactRepository.GetAll()
                    .Where(i => !i.IsDeleted && i.UserId == request.UserId && 
                           i.ObjType == request.ObjType && i.ObjId == request.ObjId)
                    .ToListAsync(cancellationToken);

                // 构建互动状态
                var status = new UserInteractStatusDto
                {
                    IsLiked = interacts.Any(i => i.Action == "like"),
                    IsFavorited = interacts.Any(i => i.Action == "fav"),
                    IsFollowed = interacts.Any(i => i.Action == "follow")
                };

                return new ApiResult<UserInteractStatusDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取用户互动状态成功",
                    Data = status
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户互动状态时发生异常");
                return new ApiResult<UserInteractStatusDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取用户互动状态失败：" + ex.Message
                };
            }
        }
    }
} 